using Enyim.Caching;
using MemcachedDemo.Host.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Distributed;
using System.Text.Json;

namespace MemcachedDemo.Host.Controllers;

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    private static readonly string[] Summaries = new[]
    {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

    private readonly IMemcachedClient _memcachedClient;
    private readonly IDistributedCache _distributedCache;

    public WeatherForecastController(IMemcachedClient memcachedClient, IDistributedCache distributedCache)
    {
        _memcachedClient = memcachedClient;
        _distributedCache = distributedCache;
    }

    [HttpGet("Memcached")]
    public async Task<IEnumerable<WeatherForecast>> GetFromMemcachedAsync()
    {
        var cacheKey = "weatherForecasts";
        var result = await _memcachedClient.GetAsync<IEnumerable<WeatherForecast>>(cacheKey);
        if (result.Success)
        {
            return result.Value;
        }

        var weatherForecasts = Enumerable.Range(1, 5)
            .Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = Random.Shared.Next(-20, 55),
                Summary = Summaries[Random.Shared.Next(Summaries.Length)]
            })
            .ToArray();
        await _memcachedClient.AddAsync(cacheKey, weatherForecasts, 300);
        return weatherForecasts;
    }

    [HttpGet("DistriutedCache")]
    public async Task<IEnumerable<WeatherForecast>> GetFromDistributedCacheAsync()
    {
        var cacheKey = $"weatherForecasts";
        var result = await _distributedCache.GetStringAsync(cacheKey);
        if (result != null)
        {
            return JsonSerializer.Deserialize<IEnumerable<WeatherForecast>>(result);
        }

        var weatherForecasts = Enumerable.Range(1, 5)
            .Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = Random.Shared.Next(-20, 55),
                Summary = Summaries[Random.Shared.Next(Summaries.Length)]
            })
            .ToArray();
        var weatherForecastsJson = JsonSerializer.Serialize(weatherForecasts);
        await _distributedCache.SetStringAsync(cacheKey, weatherForecastsJson, new DistributedCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromMinutes(5)));
        return weatherForecasts;
    }
}